4 -1
It is common for a program to access the elements of an ArrayList
one by one, in order.
This can be done using a counting loop (as has been done so far this chapter).
However,
an Iterator
object
may also be used.
To get an Iterator
object for a ArrayList
use
this method:
Iterator iterator() // Returns an iterator
An iterator object is used to visit the elements of the list
one by one.
This is sometimes more convenient than writing a loop.
An iterator implements the Iterator<E>
interface,
andr has the following methods:
boolean hasNext() // Return true if not all elements have been visited E next() // Returns the next element of the list. void remove() // Remove from the list the element just returned by next()
Here is a program that prints out every element in the ArrayList
:
import java.util.* ; class IteratorExample { public static void main ( String[] args) { ArrayList<String> names = new ArrayList<String>(); names.add( "Amy" ); names.add( "Bob" ); names.add( "Chris" ); names.add( "Deb" ); names.add( "Elaine" ); names.add( "Frank" ); names.add( "Gail" ); names.add( "Hal" ); Iterator iter = names.iterator(); while ( iter.hasNext() ) System.out.println( iter.next() ); } }
There are several
classes in the Java libraries that implement the Iterator<E>
interface.
Some classes are complicated, and a simple loop can't be used to
access all their elements.
For those classes, an iterator is very convenient.
Can primitive types, like int
and double
be
added to an ArrayList
?